/**
 * @file
 * Attaches behaviors for the Contextual module.
 */

(function ($) {

    Green.contextualLinks = Green.contextualLinks || {};

    /**
 * Attaches outline behavior for regions associated with contextual links.
 */
    Green.behaviors.contextualLinks = {
        setup: function () {
            $('div.contextual-links-wrapper').each(function () {
                var $wrapper = $(this);
                var $region = $wrapper.closest('.block').addClass('contextual-links-region');
                var $links = $wrapper.find('ul.contextual-links');
                var $trigger = $('<a class="contextual-links-trigger" href="#" />').text(Green.t('Configure')).click(function () {
                    $links.stop(true, true).slideToggle(100);
                    $wrapper.toggleClass('contextual-links-active');
                    return false;
                });
                // Attach hover behavior to trigger and ul.contextual-links.
                $trigger.add($links).hover(
                    function () {
                        $region.addClass('contextual-links-region-active');
                    },
                    function () {
                        $region.removeClass('contextual-links-region-active');
                    }
                    );
                // Hide the contextual links when user clicks a link or rolls out of the .contextual-links-region.
                $region.bind('mouseleave click', Green.contextualLinks.mouseleave);
                // Prepend the trigger.
                $wrapper.prepend($trigger).show();
            });
        }
    };

    /**
 * Disables outline for the region contextual links are associated with.
 */
    Green.contextualLinks.mouseleave = function () {
        $(this)
        .find('.contextual-links-active').removeClass('contextual-links-active')
        .find('ul.contextual-links').hide();
    };

})(jQuery);
